package com.itany.netclass.controller;

import com.itany.mvc.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Author:sjy@itany.com
 * Date:2021/9/30 10:35
 * Version:1.0-SNAPSHOT
 */
@RequestMapping("/code")
public class CodeController {

    @RequestMapping("/show")
    public void showCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        // 在内存中创建一个用于存放图像数据的画板
        BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);

        // 获取该画板中的画笔,用于在图像上绘制内容
        Graphics graphics = image.getGraphics();
        // 设置画笔所填充的矩形背景
        graphics.fillRect(0,0,50,25);
        // 设置画笔的颜色,随机色
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // 设置字体
        graphics.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));

        // 绘制内容,要求是英文字母或者数字
        String s = "qwertyuiopasdfghjklzxcvbnm0123456789";
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 4; i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        // 将生成的验证码内容存放到session中,便于校验
        request.getSession().setAttribute("code",buffer.toString());
        System.out.println("验证码: "+buffer);
        // 将用于验证码的字符串通过画笔使用指定的颜色与字体绘制到画板中
        graphics.drawString(buffer.toString(),5,18);
        // 输出到页面中
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }

}
